package demo.hexToByte;

import java.sql.PreparedStatement;
import java.util.Arrays;

public class Main {

    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    public static byte hexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    public static byte[] hexToByteArray(String inHex) {
        int hexLen = inHex.length();
        byte[] ans;
        if (hexLen % 2 == 1) {
            ++hexLen;
            inHex = "0" + inHex;
        }
        ans = new byte[hexLen / 2];
        int j = 0;
        for (int i = 0; i < hexLen; i += 2) {
            ans[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return ans;
    }

    public static void main(String[] args) {
        String hexStr = "02";
        System.out.println(hexToByte(hexStr));
        System.out.println(byteToHex((byte) 'B'));

        String hexLongStr = "014280";
        byte[] bytes = hexToByteArray(hexLongStr);
        for (byte aByte : bytes) {
            System.out.println(aByte + " : " + ((char) aByte));
        }
    }
}
